#include "ClientUdp.hpp"

int ClientUdp::SendToOrRecvFrom()
{
  int ret;
  std::string str;

  str = WriteBuf;
  if ((ret = Udp->SendTo(FdSocketSend, SinTargetSend, WriteBuf, str.size())) > 0)
    {
      memset(WriteBuf, 0, 1024);
      return ret;
    }
  if (Udp->RecvFrom(FdSocketRecv, SinTargetRcv, ReadBuf, 1024) > 0)
    memset(WriteBuf, 0, 1024);
  return ret;
}

ClientUdp::ClientUdp(int port)
  : 
#ifdef			__unix__
  Udp(new UdpUnix()),
#else
  Udp(new UdpWin()),
#endif
  Port(port),
  SinSource(port + 1),
  SinTargetSend(port),
  SinTargetRcv(port)
{
  memset(ReadBuf, 0, 1024);
  memset(WriteBuf, 0, 1024);
  memset(reinterpret_cast<char *>(&(SinSource.GetSin())), 0, sizeof(SinSource.GetSin()));
  Udp->OpenSocket(FdSocketSend);
  Udp->OpenSocket(FdSocketRecv);
  SinTargetSend.InitUdpSiClTarget();
  SinSource.InitUdpSiSr();
  Udp->SetSockNonBlocking(FdSocketSend);
  Udp->SetSockNonBlocking(FdSocketRecv);
  Udp->Bind(FdSocketRecv, SinSource);
}

ClientUdp::~ClientUdp()
{

}

int ClientUdp::AddWrite(char *buff,
			int sizeBuf)
{
  int   i;
  
  for (i = 0; i < sizeBuf; ++i)
    WriteBuf[i] = buff[i];
  return (0);
}

int ClientUdp::Run()
{
  std::string str;

  AddWrite((char*)"Pong", 5);
  while (1)
    {
      SendToOrRecvFrom();
      if ((str = ReadBuf) != "")
	{
	  std::cout << ReadBuf << std::endl;
	  memset(ReadBuf, 0, 1024);
	  AddWrite((char*)"Pong", 5);
	}
    }
  return 0;
}
